package myauctioneer.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import myauctioneer.App;
import myauctioneer.dto.User;
import myauctioneer.service.UserService;
import java.util.ArrayList;

/**
 * Servlet for Administration tasks
 */
@javax.servlet.annotation.WebServlet("/admin/*")
public class AdminServlet extends DefaultServlet {
	private static final long serialVersionUID = 1L;

	public void manageUsersAction(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		if(! this.checkAdminPriv(request))
			return;

		request.setAttribute("uAL", (new myauctioneer.dao.UserDAO()).loadAllUsers());
		request.setAttribute("template", "manageUsers.jsp");
	}

	public void removeUserAction(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		if(! this.checkAdminPriv(request))
			return;

		int id = Integer.parseInt(request.getParameter("user_id"));

		UserService userService = new UserService();

		if (userService.remove(id)) {
			request.setAttribute("title", "Successfull:");
			request.setAttribute("content", "User removed.");
		} else {
			request.setAttribute("title", "Error:");
			request.setAttribute("content", "User not removed.");
		}

		request.setAttribute("template", "success.jsp");
	}

	protected boolean checkAdminPriv(HttpServletRequest request)
	{
		User user = (User) request.getSession().getAttribute("user");

		if(user != null && user.isAdmin())
			return true;

		request.setAttribute("title", "Error:");
		request.setAttribute("content", "Access denied.");
		request.setAttribute("template", "success.jsp");

		return false;
	}
}
